package com.dy.service.impl;

import com.dy.domain.FenLei;
import com.dy.domain.pojo.PageBean;
import com.dy.mapper.FenleiMapper;
import com.dy.service.FenLeiService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

@Service
@Transactional
public class FenLeiServiceImpl implements FenLeiService {

    @Autowired
    private FenleiMapper fenleiMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public PageBean<FenLei> findPage(Integer pageNo, Integer pageSize, String ming) {

        PageHelper.startPage(pageNo,pageSize);

        List<FenLei> list = fenleiMapper.mohu(ming);

        PageInfo<FenLei> info = new PageInfo<>(list);

        PageBean<FenLei> pageBean = new PageBean<>();

        pageBean.setPageCount(info.getPages());
        pageBean.setTotalCount(info.getTotal());
        pageBean.setObject(info.getList());

        return pageBean;

    }

    @Override
    public void add(FenLei fenLei) throws JsonProcessingException {

        fenleiMapper.add(fenLei);
        redisTemplate.boundValueOps("shu").set(new ObjectMapper().writeValueAsString(fenleiMapper.findall()));

    }

    @Override
    public FenLei huixian(Integer id) {

        return fenleiMapper.huixian(id);
    }

    @Override
    public void update(FenLei fenLei) throws JsonProcessingException {

        fenleiMapper.update(fenLei);
        redisTemplate.boundValueOps("shu").set(new ObjectMapper().writeValueAsString(fenleiMapper.findall()));
    }

    @Override
    public void del(Integer id) throws JsonProcessingException {

        fenleiMapper.del(id);
        redisTemplate.boundValueOps("shu").set(new ObjectMapper().writeValueAsString(fenleiMapper.findall()));
    }

    @Override
    public List<FenLei> findall() throws IOException {
        String shu = (String)redisTemplate.boundValueOps("shu").get();

        ObjectMapper objectMapper = new ObjectMapper();

        List<FenLei> list = null;

        if (shu != null && shu.length() > 0){

            list = objectMapper.readValue(shu, new TypeReference<List<FenLei>>() {});
        }else{

            list = fenleiMapper.findall();
            redisTemplate.boundValueOps("shu").set(objectMapper.writeValueAsString(list));
        }
        return list;
    }
}
